package com.guli.auth.controller;

import com.guli.auth.service.LoginService;
import com.guli.auth.vo.UserLoginVo;
import com.guli.auth.vo.UserRegisterVo;
import com.guli.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private LoginService loginService;

    /**
     * 若session已存在，则直接跳转到首页
     * @param httpSession
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession httpSession) {
        Object loginUser = httpSession.getAttribute("loginUser");
        if (loginUser == null) {
            return "login";
        }
        return "redirect:http://gulimall.com";
    }

    /**
     * 获取短信验证码
     * @param phone
     * @return
     */

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam(value = "phone") String phone) {
        Boolean sendCode = loginService.sendCode(phone);
        return R.ok().put("data", sendCode);
    }

    /**
     * TODO session原理，将数据放在session中，只要跳到下一个网页取出数据后，session里面的数据就会删掉
     * TODO 分布式下session问题
     * RedirectAttributes redirectAttributes 模拟重定向携带数据
     * @param registerVo
     * @param result
     * @param redirectAttributes
     * @return
     */


    @PostMapping("/register")
    public String register(@Validated @ModelAttribute UserRegisterVo registerVo, BindingResult result,
                           RedirectAttributes redirectAttributes) {
        String resultPath = loginService.register(registerVo, result, redirectAttributes);
        return resultPath;
    }

    /**
     * 登录账号
     * @param userLoginVo
     * @param session
     * @return
     */

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, HttpSession session) {
        String result = loginService.login(userLoginVo, session);
        return result;
    }
}
